﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using PMS.IServices;
using PMS.Models.Base;
using PMS.Services;
using PMS.Utils;

namespace PMS.EasyUI.Areas.Base.Controllers
{
    public class BasePowerController : Controller
    {
        IBasePowerService _BasePowerService = new BasePowerService();

        IBaseMenuService _baseMenuService = new BaseMenuService();

        // GET: Base/BasePower
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetList()
        {
            string id = Request.Form["Id"] ?? "0";

            Hashtable ht = new Hashtable();
            ht.Add("ParentId", id);
            var data = _BasePowerService.GetList(ht);

            return Json(new { total = data.Count, rows = data }, "text/html", JsonRequestBehavior.AllowGet);

        }


        public ActionResult Add()
        {
            string addType = Request.QueryString["AddType"] ?? "0";
            ViewBag.AddType = addType;
            BasePower dict = new BasePower();
            return View(dict);
        }


        [HttpPost]
        public ActionResult AddOrEdit(BasePower dict)
        {
            //转换数据库不允许有null出现
            //if (dict.ParentId == 0)
            //{
            //    dict.ParentName = "";
            //    dict.Path = "";
            //    dict.PathName = "";
            //}

            if (dict.Id > 0)
            {
                ModelExtend<BasePower>.SetModifyCommAll(dict);
                if (dict.ParentId == 0)
                {
                    dict.ParentName = "";
                    dict.Path = "";
                    dict.PathName = "";
                }

                int res = _BasePowerService.Edit(dict);
                if (res > 0)
                {
                    return Json(Result.Success, "text/html", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                ModelExtend<BasePower>.SetAddCommAll(dict);
                if (dict.ParentId == 0)
                {
                    dict.ParentName = "";
                    dict.Path = "";
                    dict.PathName = "";
                }

                //ParentId 的Model的IsLeaf更新为1
                //int okOrNo = _BasePowerService.AddEditParent(dict.ParentId);
                int res = _BasePowerService.Add(dict);
                if (res > 0)
                {
                    return Json(Result.Success, "text/html", JsonRequestBehavior.AllowGet);
                }
            }

            return Json(Result.Error, "text/html", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit()
        {
            string type = Request.QueryString["Type"] ?? "0";
            ViewBag.Type = type;
            int Id = (Request.QueryString["Id"] ?? "0").ToInt32();
            BasePower dict = _BasePowerService.Dtl(id: Id);
            return View(dict);
        }

        public ActionResult Delete()
        {
            int Id = (Request.Form["Id"] ?? "0").ToInt32();
            BasePower dict = _BasePowerService.Dtl(Id);
            int res = _BasePowerService.Delete(Id, Session["UserId"].ToString());
            if (res > 0)
            {
                //_BasePowerService.DeleteEditParent(dict.ParentId);
                return Json(Result.Success, "text/html", JsonRequestBehavior.AllowGet);
            }

            return Json(Result.Error, "text/html", JsonRequestBehavior.AllowGet);

        }


        /// <summary>
        /// 根据菜单生成权限仅添加
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPower()
        {
            try
            {
                Hashtable ht = new Hashtable { { "Enable", 1 }, { "ParentId", 0 } };
                List<BaseMenu> menus = _baseMenuService.GetList(ht);
                GeneratePower(menus, 0);
                return Json(Result.Error, "text/html", JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(Result.Error, "text/html", JsonRequestBehavior.AllowGet);
            }


        }

        /// <summary>
        /// 根据菜单同步权限 完全同步
        /// </summary>
        /// <returns></returns>
        public ActionResult SynchronousPower()
        {
            return View();
        }


        /// <summary>
        /// 递归根据菜单生成对应权限
        /// </summary>
        /// <param name="powers"></param>
        public void GeneratePower(List<BaseMenu> menus, int powerId)
        {

            BasePower parentPower = _BasePowerService.Dtl(powerId);
            foreach (BaseMenu menu in menus)
            {
                //如果大于零则说明 菜单已经存在过了。 不用在次添加
                if (_BasePowerService.GetList(new Hashtable { { "MenuId", menu.Id } }).Count <= 0)
                {

                    //添加当前菜单
                    BasePower power = new BasePower();
                    PMS.Utils.ModelExtend<BasePower>.SetAddCommAll(power);
                    power.IsLeaf = 1;
                    power.MenuId = menu.Id;
                    power.ParentId = powerId;
                    power.PowerName = menu.Title;
                    power.ParentName = powerId == 0 ? "" : parentPower.PowerName;
                    power.Path = powerId == 0 ? "" :
                        parentPower.ParentId == 0 ? "." + parentPower.Id + "." : parentPower.Id + ".";
                    power.PathName = powerId == 0 ? "" :
                        parentPower.ParentId == 0 ? "." + parentPower.PowerName + "." :
                        parentPower.PathName + parentPower.PowerName + ".";
                    power.Sym = menu.Sym;
                    power.Value = menu.Value;
                    _BasePowerService.Add(power);
                    int Id = _BasePowerService.GetMaxId();
                    List<BaseMenu> childMenus = _baseMenuService.GetList(new Hashtable { { "ParentId", menu.Id } });

                    if (childMenus.Count > 0)
                    {
                        //递归循环
                        GeneratePower(childMenus, Id);
                    }
                    else
                    {
                        //添加 查看 修改 删除权限
                        string[] curdEN = new string[] { "_Read", "_Edit", "_Delete" };
                        string[] curdCN = new string[] { "_只读", "_修改", "_删除" };
                        for (int i = 0; i < curdEN.Length; i++)
                        {
                            BasePower powerCurd = new BasePower();
                            Utils.ModelExtend<BasePower>.SetAddCommAll(powerCurd);
                            powerCurd.PowerName = menu.Title + curdCN[i];
                            powerCurd.IsLeaf = 0;
                            powerCurd.ParentId = Id;
                            powerCurd.ParentName = power.PowerName;
                            powerCurd.Sym = power.Sym + curdEN[i];
                            powerCurd.MenuId = power.MenuId;
                            powerCurd.Path = power.Path + Id + ".";
                            powerCurd.PathName = power.PathName + power.PowerName + ".";
                            powerCurd.Value = "";
                            _BasePowerService.Add(powerCurd);
                        }
                    }

                }
                //如果已经存在那么更新数据
                else
                {
                    BasePower power = _BasePowerService.GetList(new Hashtable { { "MenuId", menu.Id } }).ToList()
                        .FirstOrDefault();
                    PMS.Utils.ModelExtend<BasePower>.SetModifyCommAll(power);
                    power.IsLeaf = 1;
                    power.MenuId = menu.Id;
                    power.ParentId = powerId;
                    power.PowerName = menu.Title;
                    power.ParentName = powerId == 0 ? "" : parentPower.PowerName;
                    power.Path = powerId == 0 ? "" :
                        parentPower.ParentId == 0 ? "." + parentPower.Id + "." : parentPower.Id + ".";
                    power.PathName = powerId == 0 ? "" :
                        parentPower.ParentId == 0 ? "." + parentPower.PowerName + "." :
                        parentPower.PathName + parentPower.PowerName + ".";
                    power.Sym = menu.Sym;

                    power.Value = menu.Value;
                    _BasePowerService.Edit(power);
                    int Id = _BasePowerService.GetMaxId();

                    List<BaseMenu> childMenus = _baseMenuService.GetList(new Hashtable { { "ParentId", menu.Id } });
                    if (childMenus.Count > 0)
                    {
                        int[] powerIds = _BasePowerService.GetList(new Hashtable { { "ParentId", power.Id } }).ToList()
                            .Select(x => x.Id).ToArray();
                        _BasePowerService.Delete(powerIds, "1");
                        //递归循环
                        GeneratePower(childMenus, Id);
                    }
                }
            }
        }
    }
}